package com.xhblogs.book.controller;


import com.xhblogs.book.service.BorrowService;
import com.xhblogs.book.utils.ResultUtils;
import com.xhblogs.book.utils.StatusCode;
import lombok.AllArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@CrossOrigin
@RequestMapping("/api/v1/borrow")
public class BorrowBookController {

    @Autowired
    private BorrowService borrowService;

    @ResponseBody
    @PostMapping("/borrow")
    public Object bookBorrow(
//                            @RequestParam("userId") int userId
//                            , @RequestParam("bookId") int bookId
//                            , @RequestParam("date") Date date
                            @RequestBody Map<String, Integer> map1
                            ) {
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        int status = borrowService.BorrowBook(map1.get("userId"), map1.get("bookId"), date);
        HashMap<String, Object> map = new HashMap<>();

        if (status > 0) {
            map.put("isOk", true);
        }else {
            map.put("isOK", false);
        }
        return map;
    }


    @ResponseBody
    @GetMapping("/list")
    public Object borrowBookList() {
        List<Map<String, Object>> allBorrowList = borrowService.getAllBorrowList();
        return ResultUtils.success("获取成功", StatusCode.SUCCESS_CODE,allBorrowList);
    }

    @ResponseBody
    @GetMapping("/listById")
    public Object borrowBookList(@RequestParam("id") int id) {
        List<Map<String, Object>> allBorrowListById = borrowService.getAllBorrowListById(id);
        return ResultUtils.success("获取成功", StatusCode.SUCCESS_CODE,allBorrowListById);
    }

    @ResponseBody
    @PostMapping("/deleteById")
    public Object deleteById(
//                            @RequestParam("id") int id,
                            @RequestBody Map<String, Integer> data
                            ){
        HashMap<String, Object> map = new HashMap<>();
        int i = borrowService.deleteById(data.get("id"));
        if (i>0) {
            map.put("isOk", true);
        }else {
            map.put("isOk", false);
        }
        return map;
    }
}
